package com.rjpacket.supernews.app.fragments;


import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.*;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.rjpacket.supernews.app.Constants;
import com.rjpacket.supernews.app.NewsDetailActivity;
import com.rjpacket.supernews.app.R;
import com.rjpacket.supernews.app.adapters.NewsFragmentAdapter;
import com.rjpacket.supernews.app.databases.DBHelper;
import com.rjpacket.supernews.app.models.MyImages;
import com.rjpacket.supernews.app.models.News;
import com.rjpacket.supernews.app.models.NewsDetail;
import com.rjpacket.supernews.app.tasks.DetailTaskCallOnBack;
import com.rjpacket.supernews.app.tasks.RecommendNewsDetailTask;
import com.rjpacket.supernews.app.tasks.RecommendNewsTask;
import com.rjpacket.supernews.app.tasks.TaskCallOnBack;
import com.rjpacket.supernews.app.utils.DataContainer;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */

/**
 * RadioGroup 的 “推荐”
 */
public class RecommendFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2, TaskCallOnBack, AdapterView.OnItemClickListener, DetailTaskCallOnBack, View.OnClickListener {

    private PullToRefreshListView refreshView;
    private List<News> data;
    private NewsFragmentAdapter adapter;

    private DataContainer dc;

    private String channel;
    private int headerViewsCount;
    private DBHelper dbHelper;

    private int flag;

    public RecommendFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View ret = inflater.inflate(R.layout.rjp_fragment_recommend, container, false);

        Bundle argu = getArguments();

        channel = argu.getString("channel");

        refreshView = (PullToRefreshListView) ret.findViewById(R.id.pull_to_refresh_list_view);

        refreshView.setMode(PullToRefreshBase.Mode.BOTH);

        refreshView.setOnRefreshListener(this);

        ListView listView = refreshView.getRefreshableView();
        listView.setDividerHeight(0);
        listView.setCacheColorHint(Color.TRANSPARENT);
        listView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        headerViewsCount = listView.getHeaderViewsCount();
        //listItem 点击事件冲突的解决
//        listView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

        data = new LinkedList<News>();

        adapter = new NewsFragmentAdapter(getActivity(), data);

        adapter.setListener(this);

        listView.setAdapter(adapter);
//        listView.setOnItemClickListener(this);

        dc = DataContainer.getInstance();

        dbHelper = new DBHelper(getActivity());

        if (data.size() == 0) {
            //TODO 查数据库
            if (channel != null) {
                searchNewsFromDataBase(channel);

                //查完数据库依然空
                if (data.size() == 0) {
                    startTask();
                }
            }
        }

        return ret;

    }

    private void searchNewsFromDataBase(String channel) {
        List<News> newsList = null;
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        try {
            Cursor cursor = database.query("myNews", null, "channel=?", new String[]{channel}, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String jsonNews = cursor.getString(cursor.getColumnIndex("jsonNews"));
                    if (jsonNews.length() > 0) {
                        JSONObject json = new JSONObject(jsonNews);
                        dc.setStime(json.getLong("stime"));
                        dc.setSequence(json.getInt("sequence") + 1);
                        dc.setBaseUrl(json.getString("baseurl"));
                        News news = new News();
                        news.parseJSON(json);

                        newsList = news.getList();

                        //
                        for (News news1 : newsList) {

                            news1.setJson(jsonNews);

                            String nid = news1.getNid();
                            Cursor cursor1 = database.query("myDetails", null, "nid=?", new String[]{nid}, null, null, null);
                            if (cursor1 != null) {
                                if (cursor1.moveToNext()) {
                                    String jsonDetail = cursor1.getString(cursor1.getColumnIndex("jsonDetail"));
                                    if (jsonDetail.length() > 0) {
                                        JSONObject detail = null;
                                        try {
                                            detail = new JSONObject(jsonDetail);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        NewsDetail detail1 = new NewsDetail();
                                        detail1.parseJSON(detail);
                                        news1.setNewsDetail(detail1);
                                    }
                                }
                            }
                            data.add(news1);
                        }
                    }

                }
                adapter.notifyDataSetChanged();
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        database.close();
        /**
         * //继续查询详情
         for (News news1 : newsList) {
         String nid = news1.getNid();
         Cursor cursor1 = database.query("myDetails", null, "nid=?", new String[]{nid}, null, null, null);
         if(cursor1 != null && cursor1.moveToLast()) {
         String jsonDetail = cursor1.getString(cursor1.getColumnIndex("jsonDetail"));
         if (jsonDetail.length() > 0) {
         JSONObject detail = null;
         try {
         detail = new JSONObject(jsonDetail);
         } catch (JSONException e) {
         e.printStackTrace();
         }
         NewsDetail detail1 = new NewsDetail();
         detail1.parseJSON(detail);
         news1.setNewsDetail(detail1);
         }
         data.add(news1);
         }
         }
         adapter.notifyDataSetChanged();
         */
    }

    public void startTask() {
        RecommendNewsTask task = new RecommendNewsTask(this);
        // 三个参数  第一个 数目。第二个 拉加载的类型 第三个 stime，以后获得，第四个，频道，第五个，sequence，第六个，用户id
        task.execute(
                Integer.toString(dc.getLength()),
                Constants.PULL_TYPE_DOWN,
                Long.toString(dc.getStime()),
                channel,
                Integer.toString(dc.getSequence()),
                ""
        );
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        // 下拉刷新
        startTask();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        Toast.makeText(getActivity(), "上拉", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void callOnBack(Object object) {

        refreshView.onRefreshComplete();
        if (object != null && object instanceof String) {
            String string = (String) object;

            //json 数据存数据库
            insertNews(string);

            try {
                //////////解析出返回数据的stime，sequence
                JSONObject result = new JSONObject(string);

                int status = result.getInt("status");
                if (status == 1) {
                    dc.setStime(result.getLong("stime"));
                    dc.setSequence(result.getInt("sequence") + 1);
                    dc.setBaseUrl(result.getString("baseurl"));

                    News news = new News();
                    news.parseJSON(result);
                    List<News> newsList = news.getList();

                    data.addAll(0, newsList);
                    adapter.notifyDataSetChanged();

                    for (int i = 0; i < newsList.size(); i++) {
                        //TODO 继续开线程下载详情
                        News item = newsList.get(i);

                        item.setJson(string);

                        // 继续开线程下载详情
                        String nid = item.getNid();
                        String sourceDb = Integer.toString(item.getDb());
                        String uid = "";
                        RecommendNewsDetailTask task = new RecommendNewsDetailTask(this);
                        task.execute(nid, sourceDb, uid, i + "");
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            //TODO 请检查网络
            Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
        }
    }

    private void insertNews(String result) {
        if (result != null) {
            SQLiteDatabase database = dbHelper.getWritableDatabase();

            database.beginTransaction();
            try {
                ContentValues values = new ContentValues();

                values.put("jsonNews", result);
                values.put("channel", channel);

//                int update = database.update("myNews", values, "channel = ?", new String[]{channel});
//
//                if(update == -1){
                database.insert("myNews", null, values);
//                }

                database.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                database.endTransaction();
            }
            database.close();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //TODO 推荐页面的listView item点击事件,跳转
        Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
        intent.putExtra("news", data.get(position - headerViewsCount));
        startActivity(intent);
    }

    @Override
    public void callBack(Object object, String position) {
        if (object != null && object instanceof String) {
            String string = (String) object;

            JSONObject json = null;
            try {
                json = new JSONObject(string);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            NewsDetail detail = new NewsDetail();
            detail.parseJSON(json);
            News news = data.get(Integer.parseInt(position));

            // 存数据库
            insertDeatils(string, news.getNid());

            news.setNewsDetail(detail);
        }
    }

    private void insertDeatils(String json, String nid) {
        if (json != null) {
            SQLiteDatabase database = dbHelper.getWritableDatabase();

            database.beginTransaction();
            try {
                ContentValues values = new ContentValues();

                values.put("jsonDetail", json);
                values.put("nid", nid);

                database.insert("myDetails", null, values);

                database.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                database.endTransaction();
            }
            database.close();
        }
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        int tag = (Integer) v.getTag();
        switch (id) {
            case R.id.news_title:
                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                intent.putExtra("news", data.get(tag));
                startActivity(intent);
                break;
            case R.id.list_item_save:
                News news = data.get(tag);

                String nid1 = news.getNid();

                String json = news.getJson();
                SQLiteDatabase database = dbHelper.getWritableDatabase();

                Cursor cursor = database.query("myFavorite", null, "position=?", new String[]{nid1}, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    String position = cursor.getString(cursor.getColumnIndex("position"));
                    if (nid1.equals(position)) {
                        return;
                    }
                }

                database.beginTransaction();
                try {
                    ContentValues value = new ContentValues();
                    value.put("jsonNews", json);
                    value.put("position", news.getNid());

//                    int update = database.update("myFavorite", value, "position=?", new String[]{news.getNid()});
//                    if(update == -1){
                    database.insert("myFavorite", null, value);
//                    }

                    database.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    database.endTransaction();
                }
                database.close();
                break;
            case R.id.list_item_delete:
                News news1 = data.remove(tag);
                String nid = news1.getNid();
                adapter.notifyDataSetChanged();
                SQLiteDatabase database1 = dbHelper.getWritableDatabase();
                database1.beginTransaction();
                try {
                    database1.delete("myFavorite", "position = ?", new String[]{nid});

                    database1.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    database1.endTransaction();
                }
                database1.close();
                break;
        }
    }
}
